package com.dhcc.bpm.modules.orga.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.json.JSONObject;
import com.dhcc.bpm.modules.common.entity.Plupload;
import com.dhcc.bpm.modules.common.service.IPluploadService;
import com.dhcc.bpm.modules.log.service.IGatewayLogDayService;
import com.dhcc.bpm.modules.log.vo.OrgaRankVo;
import com.dhcc.bpm.modules.orga.entity.Orga;
import com.dhcc.bpm.modules.orga.service.IAppService;
import com.dhcc.bpm.modules.orga.service.IOrgaService;
import com.dhcc.bpm.modules.orga.vo.OrgaVO;
import com.dhcc.bpm.modules.workflow.service.IWorkFlowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OrgaController
 * @Description 机构信息表 控制器
 * @Author daina
 * @Date 2020/2/24 19:25
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */
@RestController
@AllArgsConstructor
@RequestMapping("bpm-orga/orga")
@Api(value = "机构信息表", tags = "机构信息表接口")
public class OrgaController extends BladeController {

    private IOrgaService orgaService;

    private IAppService appService;

    private IGatewayLogDayService gatewayLogDayService;

    private IWorkFlowService iWorkFlowService;
    @Autowired
    private IPluploadService pluploadService;

    /**
     * @param orga
     * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.orga.entity.Orga>
     * @Description 详情
     * @Author daina
     * @Date 10:42 2020/2/25
     **/
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入orga")
    @ApiLog("机构信息 详情")
    @Log(title = "机构信息 详情", businessType = BusinessType.SELECT)
    public R<OrgaVO> detail(Orga orga) {
//        Orga detail = orgaService.getOne(Condition.getQueryWrapper(orga));
        OrgaVO detail = orgaService.selectDetail(orga);

        if (detail == null) {
            return R.data(null);
        }
        if (null != detail.getBusLicence() && !"".equals(detail.getBusLicence())) {
            QueryWrapper<Plupload> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_fullpath", detail.getBusLicence());
            List<Plupload> pluploadList = pluploadService.list(queryWrapper);
            if (pluploadList != null && pluploadList.size()>0) {
                detail.setBusLicenceFileId(pluploadList.get(0).getId());
                detail.setBusLicenceFileFullPath(pluploadList.get(0).getFileFullpath());
                detail.setBusLicenceStorageType(pluploadList.get(0).getStorageType());
                detail.setBusLicenceFileRealname(pluploadList.get(0).getFileRealname());
            }
        }
        if (null != detail.getOfficialLetter() && !"".equals(detail.getOfficialLetter())) {
            QueryWrapper<Plupload> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_fullpath", detail.getOfficialLetter());
            List<Plupload> pluploadList = pluploadService.list(queryWrapper);
            if (pluploadList != null && pluploadList.size()>0) {
                detail.setLetterFileId(pluploadList.get(0).getId());
                detail.setLetterFileFullPath(pluploadList.get(0).getFileFullpath());
                detail.setLetterStorageType(pluploadList.get(0).getStorageType());
                detail.setLetterFileRealname(pluploadList.get(0).getFileRealname());
            }
        }

        if (null != detail.getOtherFiles() && !"".equals(detail.getOtherFiles())) {
            QueryWrapper<Plupload> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_fullpath", detail.getOtherFiles());
            List<Plupload> pluploadList = pluploadService.list(queryWrapper);
            if (pluploadList != null && pluploadList.size()>0) {
                detail.setOtherFileId(pluploadList.get(0).getId());
                detail.setOtherFileFullPath(pluploadList.get(0).getFileFullpath());
                detail.setOtherStorageType(pluploadList.get(0).getStorageType());
                detail.setOtherFileRealname(pluploadList.get(0).getFileRealname());
            }
        }

        return R.data(detail);
    }

    /**
     * @param apiRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.orga.entity.Orga>>
     * @Description 分页 机构信息表
     * @Author daina
     * @Date 10:42 2020/2/25
     **/
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入orga")
    @ApiLog("机构信息 分页")
    @Log(title = "机构信息 分页", businessType = BusinessType.SELECT)
    public R<IPage<OrgaRankVo>> list(OrgaRankVo apiRankVo, Query query) {
        apiRankVo.setEnv("0"); // 环境标志 0--生产环境

        IPage<OrgaRankVo> pagesVO = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
        // 统计api 信息  (响应次数  、响应成功率、响应时间)
        if (pagesVO.getRecords() != null && pagesVO.getRecords().size() > 0) {
            for (OrgaRankVo orgaVO : pagesVO.getRecords()) {
//                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
//
//                // 求成功率
//                String successRateStr = "0.00%";
//                double successRate = 0;
//                if (orgaVO.getNum() != 0) {
//                    successRate = (double) orgaVO.getSuccessNum() / orgaVO.getNum() * 100;//返回的是String类型
//                    successRateStr = FormatUtils.doubleFormat(successRate) + "%";
//                }
//
//                // 平均响应时间
//                double avgResTime = 0.00;
//                if (orgaVO.getLineNum() != 0) {
//                    avgResTime = Double.valueOf(df.format(orgaVO.getResponseTime() / orgaVO.getLineNum()));
//                }
//
//                orgaVO.setSuccessRate(successRateStr);
//                orgaVO.setResponseTime(avgResTime);
//                //机构变更未审核数量
                orgaVO.setChangeNum(orgaService.changeNum(orgaVO.getId()));
            }
        }
        return R.data(pagesVO);
    }

    /**
     * @param orga
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.orga.vo.OrgaVO>>
     * @Description 分页 api 下 已订阅机构信息表
     * @Author daina
     * @Date 10:42 2020/2/25
     **/
    @GetMapping("/apiList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入orga")
    @ApiLog("分页 api 下 已订阅机构信息表")
    @Log(title = "分页 api 下 已订阅机构信息表", businessType = BusinessType.SELECT)
    public R<IPage<OrgaVO>> apiList(OrgaVO orga, Query query) {
        IPage<OrgaVO> pages = orgaService.apiList(Condition.getPage(query), orga);
        return R.data(pages);
    }

    /**
     * @param orga
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.orga.vo.OrgaVO>>
     * @Description 查询机构变更信息
     * @Author sjm
     * @Date 14:22 2020/2/25 0025
     **/
    @GetMapping("/ChangeList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入orga")
    @ApiLog("机构信息 分页")
    @Log(title = "机构信息 分页", businessType = BusinessType.SELECT)
    public R<IPage<OrgaVO>> changeList(OrgaVO orga, Query query) {
        IPage<OrgaVO> pages = orgaService.changeList(Condition.getPage(query), orga);
        return R.data(pages);
    }

    /**
     * @param orga
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.orga.entity.Orga>>
     * @Description 分页 机构信息表
     * @Author daina
     * @Date 10:42 2020/2/25
     **/
    @GetMapping("/costFetchList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入orga")
    @ApiLog("机构信息 分页")
    @Log(title = "机构信息 分页", businessType = BusinessType.SELECT)
    public R<IPage<Orga>> costFetchList(@ApiIgnore @RequestParam Map<String, Object> orga, Query query) {
        orga.put("operationType", "1");
        orga.put("authFlag", "1");
        IPage<Orga> pages = orgaService.page(Condition.getPage(query), Condition.getQueryWrapper(orga, Orga.class));
        return R.data(pages);
    }

    /**
     * @param orga
     * @param bladeUser
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.orga.entity.Orga>>
     * @Description 接入日期排序获取机构列表
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @GetMapping("/listAll")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "机构信息 列表", notes = "传入orga")
    @ApiLog("机构信息 列表")
    @Log(title = "机构信息 列表", businessType = BusinessType.SELECT)
    //@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
    public R<List<Orga>> listAll(Orga orga, BladeUser bladeUser) {
        QueryWrapper<Orga> queryWrapper = Condition.getQueryWrapper(orga);
        List<Orga> list = orgaService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Orga::getTenantId, bladeUser.getTenantId()).orderByDesc(Orga::getAccessTime) : queryWrapper.lambda().orderByDesc(Orga::getAccessTime));
        return R.data(list);
    }

    /**
     * @param orga
     * @param bladeUser
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.orga.entity.Orga>>
     * @Description 下拉机构
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @GetMapping("/select")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "下拉机构名称", notes = "传入orga")
    @ApiLog("机构信息 下拉机构名称")
    @Log(title = "机构信息 下拉机构名称", businessType = BusinessType.SELECT)
    //@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
    public R<List<Orga>> select(Orga orga, BladeUser bladeUser) {
        QueryWrapper<Orga> queryWrapper = Condition.getQueryWrapper(orga);
        List<Orga> list = orgaService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Orga::getTenantId, bladeUser.getTenantId()) : queryWrapper);
        return R.data(list);
    }

    /**
     * @param orga
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.orga.vo.OrgaVO>>
     * @Description 自定义分页 机构信息表
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @GetMapping("/page")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "分页", notes = "传入orga")
    @ApiLog("机构信息 分页")
    @Log(title = "机构信息 分页", businessType = BusinessType.SELECT)
    public R<IPage<OrgaVO>> page(OrgaVO orga, Query query) {
        IPage<OrgaVO> pages = orgaService.selectOrgaPage(Condition.getPage(query), orga);
        return R.data(pages);
    }

    /**
     * @param orga
     * @return org.springblade.core.tool.api.R
     * @Description 新增 机构信息表
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入orga")
    @ApiLog("机构信息 新增")
    @Log(title = "机构信息 新增", businessType = BusinessType.INSERT)
    public R save(@Valid @RequestBody Orga orga) {
        return R.status(orgaService.save(orga));
    }

    /**
     * @param orga
     * @return org.springblade.core.tool.api.R
     * @Description 修改 机构信息表
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入orga")
    @ApiLog("机构信息 修改")
    @Log(title = "机构信息 修改", businessType = BusinessType.UPDATE)
    public R update(@Valid @RequestBody Orga orga) {
        return R.status(orgaService.updateById(orga));
    }

    /**
     * @param orga
     * @return org.springblade.core.tool.api.R
     * @Description 新增或修改 机构信息表
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入orga")
    @ApiLog("机构信息 新增或修改")
    @Log(title = "机构信息 新增或修改", businessType = BusinessType.INSERT)
    public R submit(@Valid @RequestBody Orga orga) {
        return R.status(orgaService.saveOrUpdate(orga));
    }

    /**
     * @param orga
     * @return org.springblade.core.tool.api.R
     * @Description 新增  机构信息表
     * @Author wangjinghan
     * @Date 2022年3月31日11:43:23
     **/
    @PostMapping("/addOrga")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增", notes = "传入orga")
    @ApiLog("机构信息 新增")
    @Log(title = "机构信息 新增", businessType = BusinessType.INSERT)
    public R addOrga(@Valid @RequestBody Orga orga) {
        // detail.busLicence, '营业执照'
        // detail.officialLetter, 'IATA证书'
        // detail.otherFiles  上一年年报:
        if (null != orga.getBusLicence() && !"".equals(orga.getBusLicence())) {
            Plupload plupload = pluploadService.selectById(Long.valueOf(orga.getBusLicence()));
            if (null != plupload) {
                orga.setBusLicence(plupload.getFileFullpath());
            }
        }
        if (null != orga.getOfficialLetter() && !"".equals(orga.getOfficialLetter())) {
            Plupload plupload = pluploadService.selectById(Long.valueOf(orga.getOfficialLetter()));
            if (null != plupload) {
                orga.setOfficialLetter(plupload.getFileFullpath());
            }
        }
        if (null != orga.getOtherFiles() && !"".equals(orga.getOtherFiles())) {
            Plupload plupload = pluploadService.selectById(Long.valueOf(orga.getOtherFiles()));
            if (null != plupload) {
                orga.setOtherFiles(plupload.getFileFullpath());
            }
        }

        return orgaService.addOrga(orga);
    }

    /**
     * @param orga
     * @return org.springblade.core.tool.api.R
     * @Description 修改 机构信息表
     * @Author wangjinghan
     * @Date 2022年4月1日14:34:35
     **/
    @PostMapping("/updateOrga")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "修改", notes = "传入orga")
    @ApiLog("机构信息 修改")
    @Log(title = "机构信息 修改", businessType = BusinessType.INSERT)
    public R updateOrga(@Valid @RequestBody Orga orga) {
        if (null != orga.getBusLicence() && !"".equals(orga.getBusLicence())) {
            Plupload plupload = pluploadService.selectById(Long.valueOf(orga.getBusLicence()));
            if (null != plupload) {
                orga.setBusLicence(plupload.getFileFullpath());
            }
        }
        if (null != orga.getOfficialLetter() && !"".equals(orga.getOfficialLetter())) {
            Plupload plupload = pluploadService.selectById(Long.valueOf(orga.getOfficialLetter()));
            if (null != plupload) {
                orga.setOfficialLetter(plupload.getFileFullpath());
            }
        }
        if (null != orga.getOtherFiles() && !"".equals(orga.getOtherFiles())) {
            Plupload plupload = pluploadService.selectById(Long.valueOf(orga.getOtherFiles()));
            if (null != plupload) {
                orga.setOtherFiles(plupload.getFileFullpath());
            }
        }

        return orgaService.updateOrga(orga);
    }

    /**
     * @param ids
     * @return org.springblade.core.tool.api.R
     * @Description 删除 机构信息表
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "删除 机构信息", notes = "传入ids")
    @ApiLog("机构信息 删除")
    @Log(title = "机构信息 删除", businessType = BusinessType.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {

        String[] arrayIds = ids.split(",");

        for (String id : arrayIds) {

            List<Orga> list = orgaService.findByPId(id);
            for (Orga o : list) {
                ids = ids + "," + o.getId();
            }

        }
        //删除对应工作流
        String[] arrayIds2 = ids.split(",");
        for (String id : arrayIds2) {
            iWorkFlowService.deleteRelated("i", id);//机构认证
            iWorkFlowService.deleteRelated("k", id);//机构变更
        }
        return R.status(orgaService.deleteIdAndParentId(Func.toLongList(ids)));
//		return R.status(orgaService.deleteLogic(Func.toLongList(ids)));
    }

    /**
     * @param id
     * @return org.springblade.core.tool.api.R
     * @Description 根据产品ID查询机构
     * @Author daina
     * @Date 10:43 2020/2/25
     **/
    @PostMapping("/selectOrgaByProductId")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "根据产品ID查询机构", notes = "传入产品ID")
    @ApiLog("根据产品ID查询机构")
    @Log(title = "根据产品ID查询机构", businessType = BusinessType.SELECT)
    public R selectOrgaByProductId(@ApiParam(value = "产品ID", required = true) @RequestParam Long id) {
        return R.data(orgaService.selectOrgaByProductId(id));
    }

    /**
     * @param
     * @return org.springblade.core.tool.api.R<java.util.Map < java.lang.String, java.lang.Object>>
     * @Description 最新接入机构/机构总数/应用总数
     * @Author daina
     * @Date 10:44 2020/2/25
     **/
    @GetMapping("/newOrgaAndAllCount")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "最新接入机构/机构总数/应用总数", notes = "传入orga")
    @ApiLog("最新接入机构/机构总数/应用总数")
    @Log(title = "最新接入机构/机构总数/应用总数", businessType = BusinessType.SELECT)
    public R<Map<String, Object>> newOrgaAndAllCount(BladeUser bladeUser) {
        Map<String, Object> map = new HashMap<String, Object>();
        Query query = new Query();
        query.setSize(10);
        query.setCurrent(1);

        Orga orga = new Orga();
        orga.setAuthFlag("1");
        orga.setOperationType("1");
        QueryWrapper<Orga> queryWrapper = Condition.getQueryWrapper(orga);//根据创建时间倒排
        IPage<Orga> pages = orgaService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Orga::getTenantId, bladeUser.getTenantId()).orderByDesc(Orga::getAccessTime) : queryWrapper.lambda().orderByDesc(Orga::getAccessTime));

        orga.setAuthFlag(null);
        queryWrapper = Condition.getQueryWrapper(orga);
        int orgaCount = orgaService.countOrga();

        int appCount = appService.countApp();
        map.clear();
        List<Orga> orgaList = pages.getRecords();
        map.put("newOrgaList", orgaList);
        map.put("orgaCount", orgaCount);
        map.put("appCount", appCount);
        return R.data(map);
    }

    /**
     * @return
     * @Description 修改控制状态
     * @Author daina
     * @Date 10:44 2020/5/19
     */
    @PostMapping("/changeStatus")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入Orga")
    @ApiLog("修改控制状态")
    @Log(title = "修改控制状态", businessType = BusinessType.UPDATE)
    public R changeStatus(@Valid @RequestBody Orga orga) {
        return R.status(orgaService.updateById(orga));
    }


    /**
     * @param
     * @return com.dhcc.bpm.common.json.JSONObject
     * @Description 查询所有机构名称
     * @Author daina
     * @Date 14:40 2020/2/25
     **/
    @GetMapping("/selectByOrgaName")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "查询所有机构名称", notes = "无参")
    @Log(title = "查询所有机构名称", businessType = BusinessType.SELECT)
    @ApiLog("查询所有机构名称")
    public JSONObject selectByOrgaName() {
        JSONObject object = new JSONObject();
        object.put("success", true);
        object.put("names", orgaService.selectByOrgaName());
        return object;
    }
}
